﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Model.Helpers
{
    public class Recurrence
    {
        #region attributes

        [Key]
        public int RecurrenceID { get; set; }        
        public DayOfWeek DayOfWeekFrom { get; set; }        
        public DayOfWeek DayOfWeekTo { get; set; }        
        public bool IsAllDay { get; set; }        
        [Range(0,23)]
        public int HourFrom { get; set; }        
        [Range(0, 23)]
        public int HourTo  { get; set; }

        #endregion

        public bool IsValid(DateTime date)
        {
            DayOfWeek dayOfWeekFrom = DayOfWeekFrom;
            DayOfWeek dayOfWeekTo = DayOfWeekTo;
            DayOfWeek dateDayOfWeek = date.DayOfWeek;
            if(dayOfWeekTo < dayOfWeekFrom)
            {
                dayOfWeekTo += 7;
                if(dateDayOfWeek < DayOfWeekTo)
                    dateDayOfWeek += 7;
            }
            
            if (dateDayOfWeek < dayOfWeekFrom || dateDayOfWeek > dayOfWeekTo)
                return false;
            
            bool result = true;
            if (!IsAllDay)
            {                 
                if(dateDayOfWeek == dayOfWeekFrom)
                    result &= (date.Hour >= HourFrom);
                if(dateDayOfWeek == dayOfWeekTo)
                    result &= (date.Hour <= HourTo);
            }
            return result;
        }
    }
}
